<template>
  <div>
    <!-- 搜索栏 -->
    <search-bar :isShowDate='false'
                :left="18"
                @handleAdd="addProduct"
                btnText="添加产品"
                :isShowAdd="true"
                placeHolder="请输入产品名称"
                @handleSearch="searchData" />
    <!-- 转盘列表数据 -->
    <table-data-el :tableData="tableData.list"
                   :tableLabel="tableLabel"
                   :page.sync="page"
                   :pageCount="tableData.rows"
                   @handleRemove="removeProduct"
                   v-loading="loading"
                   @handleModify="handleModifyProduct" />
    <!-- 弹框修改数据和添加数据 -->
    <div class="fwbStyld">
      <el-dialog :visible.sync="isShowProduct"
                 title="产品信息"
                 width="50%"
                 center
                 top="5vh"
                 :close-on-click-modal="false"
                 v-el-drag-dialog
                 @close="closeAddProduct('form')"
                 :close-on-press-escape="false">
        <template>
          <el-form ref="form"
                   :model="form"
                   label-width="80px"
                   class="formWra"
                   v-loading="dialogLoading"
                   :rules="rules">
            <el-form-item label="产品名称"
                          prop="name">
              <el-input placeholder="请输入产品名称"
                        size="small"
                        v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="产品价值"
                          prop="price">
              <el-input placeholder="请输入产品价值"
                        size="small"
                        v-model="form.price"></el-input>
            </el-form-item>
            <el-form-item label="中奖概率"
                          prop="prob">
              <el-input placeholder="请输入中奖概率"
                        size="small"
                        v-model="form.prob"></el-input>
            </el-form-item>
            <el-form-item label="领取方式"
                          prop="draw">
              <el-radio v-model="form.draw"
                        size="mini"
                        label="1">到店领取</el-radio>
              <el-radio v-model="form.draw"
                        size="mini"
                        label="0">邮寄到家</el-radio>
            </el-form-item>
            <el-form-item label="产品图片"
                          prop="image">
              <el-upload class="avatar-uploader"
                         :show-file-list="false"
                         list-type="picture-card"
                         action="https://ceshi.ctbls.com/manage/SetBangController/GiftFile"
                         :on-success="handleAvatarSuccess"
                         :on-preview="beforeAvatarUpload"
                         name="image"
                         :headers="obj">
                <img v-if="form.image"
                     :src="form.image"
                     class="avatar">
                <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="产品描述"
                          prop="content">
              <fwb :height="200"
                   v-model="form.content"
                   v-if="isShowProduct"></fwb>
            </el-form-item>
          </el-form>
        </template>
        <template slot="footer">
          <el-button type="primary"
                     @click="confirmAddProduct('form')">保存</el-button>
          <el-button type="danger"
                     @click="closeAddProduct('form')">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
    import {getToken} from '@/utils/auth'
    import tableDataEl from '@/views/Setup/common/table'
    //富文本编辑器
    import fwb from '@/components/Tinymce/Tinymce'

    export default {
  name: "setTurntable",
  data () {
    return {
      tableData: {}, //转盘赠品列表数据
      tableLabel: [ //转盘表格数据对应的标题
        {
          label: '产品图片',
          prop: 'image',
          image: true
        },
        {
          label: '产品名称',
          prop: 'name'
        },
        {
          label: '产品价值',
          prop: 'price'
        },
        {
          label: '中奖概率',
          prop: 'prob'
        },
        {
          label: '领取方式',
          prop: 'draw',
          mode: true
        },
        {
          label: '操作',
          prop: 'id',
          operate: true
        }
      ],
      page: 1, //当前页
      pageSize: 8, //每页显示多少条数据
      searchkey: '',//搜索关键字
      isShowProduct: false, //弹框显示或隐藏
      obj: {  //上传图片配置请求头用到的Token
        Authorization: getToken()
      },
      content: 'Hello', //富文本内容
      form: { //添加商品弹框内容
        name: '',
        price: '',
        prob: '',
        draw: '',
        image: '',
        content: ''
      },
      rules: { //表单验证
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '请输入产品价值', trigger: 'blur' }
        ],
        prob: [
          { required: true, message: '请输入中奖概率', trigger: 'blur' }
        ],
        draw: [
          { required: true, message: '请选择领取方式', trigger: 'submit' }
        ],
        image: [
          { required: true, message: '请上传产品图片', trigger: 'submit' }
        ],
        content: [
          { required: true, message: '请输入产品描述', trigger: 'submit' }
        ]
      },//表单验证
      rowId: '', //产品ID
      type: '',
      loading: false,
      dialogLoading: false
    }
  },
  components: {
    tableDataEl,
    fwb
  },
  methods: {
    async init (searchkey = this.searchkey) { //页面初始化
      this.loading = true;
      let paramsStr = Object.assign(searchkey,{page: this.page, pageSize: this.pageSize});
        let res = await this.api.setTurnTable(paramsStr);
      this.tableData = res.data;
      this.loading = false;
    },
    addProduct (type) {  //显示添加商品弹框
      this.type = 1;
      this.isShowProduct = true;
      this.form['content'] = '';
    },
    closeAddProduct (formName) {
      this.isShowProduct = false;
      this.$refs[formName].resetFields();
      Object.keys(this.form).map((key) => this.form[key] = '')
    },
    beforeAvatarUpload (file) { //暂时没用
      // console.log("hello")
      // this.form['image'] = file.url;
      // console.log(file)
      // console.log(this.form['image'])
    },
    handleAvatarSuccess (response, file, fileList) {  //上传图片获得路径
      // this.form['image'] = file.url //file.url本地地址  response 后台返回的网路地址
      this.form['image'] = response;
    },
    async confirmAddProduct (formName) { //添加产品
      let flag = true;
      this.$refs[formName].validate((valid) => { //验证表单数据完整性
        if (!valid) {
          this.$message('请完善产品信息！');
          flag = false;
        }
      });
      let res;
      if (flag) {
        if (this.type) {
          this.api.addProduct(this.form).then((res) => {
            this.$message({
              type: res.code === 1 ? 'success' : 'error',
              message: res.msg
            });
            this.init();
          });
        } else {
          this.api.mdfProduct(Object.assign({}, this.form, this.rowId)).then((res) => {
            this.$message({
              type: res.code === 1 ? 'success' : 'error',
              message: res.msg
            });
            this.init();
          });
        }
        this.isShowProduct = false;
      } else {
        return false;
      }


    },
    async removeProduct (id) { //删除产品
      let self = this;
      let confirm = await this.$confirm('此操作将永久删除该产品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return true
      }).catch(() => {
        return false
      });
      if (confirm) {
        let res = await this.api.removeProduct({ id }).then(res => res);
        self.$message({
          type: res.code === 1 ? 'success' : 'error',
          message: res.msg
        });
        self.init();
      }
    },
    async handleModifyProduct (id) { //修改商品
      this.type = 0;
      this.rowId = id;
      this.dialogLoading = true;
      this.isShowProduct = true;
      let res = await this.api.mdfProductBefore({ id }).then(res => res);
      res.code ? Object.assign(this.form,res.data) : this.$message({type: 'error', message: res.msg});
      this.dialogLoading = false;
    },
    searchData (...value) {
      this.init(value[0])
    }
  },
  watch: {
    page () {
      this.init()
    }
  },
  mounted () {
    this.init();
    // 配置viewer
  }
}
</script>

<style  scoped>
.avatar-uploader {
  width: 120px;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar-uploader >>> .el-upload--picture-card {
  width: 100px !important;
  height: 100px !important;
  line-height: 100px;
  overflow: hidden;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.el-form-item {
}

/* 富文本 */
.fwbStyld >>> .el-dialog--center .el-dialog__body {
  height: 75vh;
}
.fwbStyld >>> .el-dialog__footer {
  box-shadow: 0 -1px 0 0 #eee !important;
  z-index: 80000 !important;
}
/*滚动条样式*/
.fwbStyld >>> .el-dialog--center .el-dialog__body::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}
.fwbStyld >>> .el-dialog--center .el-dialog__body::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #aaa;
}
.fwbStyld >>> .el-dialog--center .el-dialog__body::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: #ededed;
}
</style>
